<%--
  Created by IntelliJ IDEA.
  User: Gao
  Date: 2024/4/15
  Time: 14:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="/static/layui/css/layui.css">
    <script src="/static/jquery-2.1.4.js" type="text/javascript" charset="utf-8"></script>
    <script src="/static/layui/layui.js" type="text/javascript" charset="utf-8"></script>
    <script src="/static/mylayer.js" type="text/javascript" charset="utf-8"></script>
    <script src="/static/kindeditor/kindeditor.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" src="/static/Ueditor/ueditor.config.js"></script>
    <!-- 编辑器源码文件 -->
    <script type="text/javascript" src="/static/Ueditor/ueditor.all.js"></script>
    <script type="text/javascript" src="/static/Ueditor/lang/zh-cn/zh-cn.js"></script>
</head>
<body>
<%--搜索form表单--%>
<form class="layui-form layui-row layui-col-space16">
    博客名：
    <div class="layui-inline layui-input-wrap">
        <div class="layui-input-prefix">
            <i class="layui-icon layui-icon-username"></i>
        </div>
        <input type="text" name="name" value="" class="layui-input" lay-affix="clear">
    </div>
    博客类型：
    <div class="layui-inline layui-input-wrap">
        <input type="text" name="address" lay-affix="clear" class="layui-input">
    </div>
    <div class="layui-inline">
        <button class="layui-btn" lay-submit lay-filter="submitSearch">Search</button>
        <button type="reset" class="layui-btn layui-btn-primary">Clear</button>
    </div>
</form>
<table class="layui-hide" id="test" lay-filter="test"></table>
<%--头部工具条--%>
<script id="toolbarDemo" type="text/html">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="deleteAll">批量删除</button>
    </div>
</script>
<%--右侧工具条--%>
<script type="text/html" id="barDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
        <a class="layui-btn layui-btn-xs" lay-event="update">编辑</a>
    </div>
</script>
<%--添加form表单--%>
<div id="addForm" style="display:none;">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">博客名</label>
            <div class="layui-input-block">
                <input type="text" name="name" lay-verify="required" placeholder="请输入" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">封面</label>
            <div class="layui-input-block">
                <div class="layui-upload">
                    <div class="layui-upload-list">
                        <img width="150px" height="150px" class="layui-upload-img" id="demo1">
                        <input type="hidden" name="image" id="imageId">
                        <p id="demoText"></p>
                    </div>
                    <button type="button" class="layui-btn" id="uploadId">上传图片</button>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">博客内容</label>
            <div class="layui-input-block">
                <textarea style="width:730px; height: 400px" id="contentId" name="content"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="submit" class="layui-btn" lay-submit lay-filter="submitAdd">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>
<%--修改form表单--%>
<div id="updateForm" style="display:none;">
    <form class="layui-form" lay-filter="updateFormFilter" action="">
        <input type="hidden" name="id">
        <div class="layui-form-item">
            <label class="layui-form-label">博客名</label>
            <div class="layui-input-block">
                <input type="text" name="name" lay-verify="required" placeholder="请输入" autocomplete="off"
                       class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">博客内容</label>
            <div class="layui-input-block">
                <textarea name="content"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="submit" class="layui-btn" lay-submit lay-filter="submitUpdate">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>

<%--table中展示图片的templet--%>
<script type="text/html" id="imageTemplet">
    <img src="/pic/{{d.image}}"></img>
</script>
<%--table中展示status的templet--%>
<script type="text/html" id="statusTemplet">
    {{#     if (d.status == 1) {                }}
    <span class="layui-badge layui-bg-green">上架</span>
    {{#     } else if (d.status == 0) {         }}
    <span class="layui-badge">下架</span>
    {{#     }                                   }}
</script>
<script type="text/html" id="statusTemplet1">
    <!-- 这里的 checked 的状态值判断仅作为演示 -->
    <input type="checkbox" name="status" value="{{= d.id }}" title="上架|下架" lay-skin="switch"
           lay-filter="demo-templet-status" {{=d.status == 1 ? "checked" : "" }}>
</script>
<script>
    layui.use(['table', 'form', 'upload'], function () {
        var form = layui.form;
        var table = layui.table;
        var upload = layui.upload;
        // 创建渲染实例
        table.render({
            elem: '#test',
            id: 'tableId',
            url: '/blog?method=selectByPage',
            toolbar: '#toolbarDemo',
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: 'id', title: 'ID', sort: true},
                {field: 'name', title: '博客名'},
                {field: 'content', title: '博客内容', escape: false},
                {field: 'click_count', title: '点击数量'},
                {field: 'image', title: '博客封面', templet: '#imageTemplet'},
                //{field: 'status', title: '状态', templet: '#statusTemplet'},
                {field: 'status', title: '状态', templet: '#statusTemplet1'},
                {fixed: 'right', title: '操作', minWidth: 125, toolbar: '#barDemo'}
            ]],
            page: true
        });


        //  状态切换 -- 传回后台
        form.on('switch(demo-templet-status)', function (obj) {
            var id = this.value;
            var name = this.name;
            var flag = obj.elem.checked
            var arr = {id, flag};
            $.post(
                '/blog?method=updateStatus',
                {'arr': arr},  //{name: 'zhyangsan', address: 'fdfd', time: 'fd'}
                function (result) {
                    console.log(result);
                    if (result.code == 0) {
                        layer.msg("修改成功")
                        table.reload('tableId');
                    } else {
                        mylayer.errorMsg("修改失败");
                    }
                },
                'json'
            );
        });

        // 搜索提交
        form.on('submit(submitSearch)', function (data) {
            var field = data.field; // 获得表单字段
            // 执行搜索重载
            table.reload('tableId', {
                page: {
                    curr: 1 // 重新从第 1 页开始
                },
                where: field // 搜索的字段
                //http://localhost:8080/blog?method=selectByPage&page=1&limit=10&name=zhansgsan&address=5&time=2014
            });
            return false; // 阻止默认 form 跳转
        });

        // 头部工具栏事件
        table.on('toolbar(test)', function (obj) {
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var othis = lay(this);
            switch (obj.event) {
                case 'add':
                    var index = layer.open({
                        type: 1,
                        title: '添加数据',
                        area: ['900px', '650px'], // 宽高
                        content: $('#addForm'),
                        success: function () {
                            $("#addForm form")[0].reset();
                            //form.render();
                            //先销毁再初始化
                            KindEditor.remove('#contentId');
                            var kindEditorParams = {
                                afterBlur: function () {
                                    this.sync();
                                }
                            };
                            KindEditor.create('#contentId', kindEditorParams);
                            var editor = KindEditor.create('#contentId', kindEditorParams);
                            //清空kindeditor的内容
                            editor.html("");

                            //图片上传
                            //常规使用 - 普通图片上传
                            var uploadInst = upload.render({
                                elem: '#uploadId'
                                , url: '/upload' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
                                , before: function (obj) {
                                    //预读本地文件示例，不支持ie8
                                    obj.preview(function (index, file, result) {
                                        $('#demo1').attr('src', result); //图片链接（base64）
                                    });
                                }
                                , done: function (result) {
                                    if (result.code == 0) {
                                        $('#imageId').val(result.data);
                                        $('#demoText').html(''); //置空上传失败的状态
                                    } else {
                                        mylayer.errorMsg(result.msg);
                                    }
                                }
                                , error: function () {
                                    //演示失败状态，并实现重传
                                    var demoText = $('#demoText');
                                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                                    demoText.find('.demo-reload').on('click', function () {
                                        uploadInst.upload();
                                    });
                                }
                            });
                            //需要渲染
                            form.render();
                        }
                    });

                    // 绑定提交事件
                    form.on('submit(submitAdd)', function (data) {
                        var field = data.field; // 获取表单字段值
                        console.log(data);
                        // 此处可执行 Ajax 等操作
                        $.post(
                            '/blog?method=add',
                            field,  //{name: 'zhyangsan', address: 'fdfd', time: 'fd'}
                            function (result) {
                                console.log(result);
                                if (result.code == 0) {
                                    mylayer.okMsg(result.msg);
                                    layer.close(index);
                                    table.reload('tableId');
                                } else {
                                    mylayer.errorMsg(result.msg);
                                }
                            },
                            'json'
                        );
                        return false; // 阻止默认 form 跳转
                    });
                    break;
                case 'deleteAll':
                    var data = checkStatus.data;
                    //[{"id":2,"name":"Java1812","address":"ddf","time":"232"},{"id":3,"name":"Java1903","address":"34","time":"323"}]
                    var ids = new Array();
                    $(data).each(function () {
                        ids.push(this.id);
                    })
                    //[2,4]
                    layer.confirm(
                        '您确认要删除么?',
                        {icon: 3},
                        function (index) {
                            $.post(
                                '/blog?method=deleteAll',
                                {'ids': ids},
                                function (result) {
                                    console.log(result);
                                    if (result.code == 0) {
                                        mylayer.okMsg(result.msg);
                                        //删除成功之后刷新表格，展示最新数据
                                        table.reload('tableId');
                                    } else {
                                        mylayer.errorMsg(result.msg);
                                    }
                                },
                                'json'
                            );
                        }
                    );
                    break;
                case 'LAYTABLE_TIPS':
                    layer.alert('自定义工具栏图标按钮');
                    break;
            }
            ;
        });

        // 触发单元格工具事件
        table.on('tool(test)', function (obj) { // 双击 toolDouble
            var data = obj.data; // 获得当前行数据
            console.log(obj);
            //{"id": 1,"name": "Java1807","address": "dfdf","time": "3434"}
            console.log(obj.data);
            if (obj.event === 'delete') {
                layer.confirm(
                    '您确认要删除么?',
                    {icon: 3},
                    function (index) {
                        $.post(
                            '/blog?method=deleteById',
                            {'id': data.id},
                            function (result) {
                                console.log(result);
                                if (result.code == 0) {
                                    mylayer.okMsg(result.msg);
                                    //删除成功之后刷新表格，展示最新数据
                                    table.reload('tableId');
                                } else {
                                    mylayer.errorMsg(result.msg);
                                }
                            },
                            'json'
                        );
                    }
                );
            } else if (obj.event === 'update') {
                var index = layer.open({
                    type: 1,
                    title: '编辑数据',
                    area: ['500px', '300px'], // 宽高
                    content: $('#updateForm').html(),
                    success: function () {
                        //form.val有两个参数，第一个是form表单的lay-filter名字，
                        //第二个参数是json对象：{"id": 1,"name": "Java1807","address": "dfdf","time": "3434"}
                        //将第二个参数的值按照“名字”映射到form表单中
                        //form.val('updateFormFilter', data);
                        $.post(
                            '/blog?method=selectById',
                            {'id': data.id},
                            function (result) {
                                if (result.code == 0) {
                                    form.val('updateFormFilter', result.data);
                                }
                            },
                            'json'
                        );
                    }
                });

                // 绑定提交事件
                form.on('submit(submitUpdate)', function (data) {
                    var field = data.field; // 获取表单字段值
                    console.log(data);
                    // 此处可执行 Ajax 等操作
                    $.post(
                        '/blog?method=update',
                        field,  //{name: 'zhyangsan', address: 'fdfd', time: 'fd'}
                        function (result) {
                            console.log(result);
                            if (result.code == 0) {
                                mylayer.okMsg(result.msg);
                                layer.close(index);
                                table.reload('tableId');
                            } else {
                                mylayer.errorMsg(result.msg);
                            }
                        },
                        'json'
                    );
                    return false; // 阻止默认 form 跳转
                });
            }
        });

    });
</script>
</body>
</html>
